package com.farm.forms.action;

import com.farm.forms.domain.Formcategory;
import com.farm.forms.domain.Query;
import com.farm.forms.domain.Rules;
import com.farm.forms.domain.Title;
import com.farm.forms.service.FormcategoryServiceInter;
import com.farm.forms.service.QueryServiceInter;
import com.farm.forms.service.RulesServiceInter;
import com.farm.forms.service.TitleServiceInter;

import com.farm.report.FarmReport;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuery.CACHE_UNIT;
import com.farm.core.sql.result.DataResult;
import com.farm.web.easyui.EasyUiUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.farm.core.page.CommitType;
import com.farm.core.page.PageSet;
import com.farm.core.page.PageType;
import com.farm.core.time.TimeTool;
import com.farm.web.WebSupport;
import com.farm.web.spring.BeanFactory;

/* *
 *功能：数据查询器控制层
 *详细：
 *
 *版本：v0.1
 *作者：王东
 *日期：20141124110140
 *说明：
 */
public class QueryAction extends WebSupport {
	private Map<String, Object> jsonResult;// 结果集合
	private Formcategory type;
	private DataQuery query;// 条件查询
	private Query entity;// 实体封装
	private PageSet pageset;// 请求状态
	private String ids;// 主键集合
	private List<Rules> rules = null;
	private List<Title> titles = null;
	private List<List<Rules>> ruleTable;
	private Map<String, List<Entry<String, String>>> enums;
	private InputStream inputStream;

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	public String queryall() {
		try {
			query = EasyUiUtils.formatGridQuery(getRequest(), query);
			DataResult result = queryIMP.createQuerySimpleQuery(query).search();
			result.runDictionary("0:否,1:是", "REPORTABLE");
			result.runDictionary("0:否,1:是", "DISTINCTABLE");
			jsonResult = EasyUiUtils.formatGridData(result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	/**
	 * 动态查询
	 * 
	 * @return
	 */
	public String query() {
		try {
			initQeuryPage();
			query = EasyUiUtils.formatGridQuery(getRequest(), query);
			query = DataQuery.init(query, entity.getFromstr(), entity
					.getSelectstr());
			if(entity.getDefaultrule()!=null&&entity.getDefaultrule().trim().length()>0){
				query.addSqlRule(" and "+entity.getDefaultrule());
			}
			if (entity.getDistinctable().equals("1")) {
				query.setDistinct(true);
			}
			if (entity.getCachetime() > 0) {
				query.setCache(entity.getCachetime(), CACHE_UNIT.minute);
			}
			initQueryRule();
			if (entity.getDefsortstr() != null
					&& entity.getDefsortstr().trim().length() > 0) {
				query.addDefaultSort(new DBSort(entity.getDefsortstr(), entity
						.getDefsorttype().equals("4") ? "DESC" : "ASC"));
			}
			DataResult result = query.search();
			initDicResult(result);

			jsonResult = EasyUiUtils.formatGridData(result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	/**
	 * 转义结果集合
	 */
	private void initDicResult(DataResult result) {
		for (Title rule : titles) {
			try {
				if (rule.getDictype().equals("1")) {
					// 枚举[type1:text1,type2:text2,...]
					result.runDictionary(rule.getDicpara().trim(), rule
							.getFieldname().trim());
				}
				if (rule.getDictype().equals("2")) {
					// 数据字典[key]
					result.runDictionary(getDictionary(rule.getDicpara().trim()),
							rule.getFieldname().trim());
				}
				if (rule.getDictype().equals("3")) {
					// 日期[yyyyMMddHHmmss]
					result.runformatTime(rule.getFieldname().trim(), rule
							.getDicpara().trim());
				}
			} catch (Exception e) {
				log.error("动态表单数据转义错误！" + e.getMessage());
			}
		}
	}

	/**
	 * 初始化查询条件
	 */
	private void initQueryRule() {
		for (Rules rule : rules) {
			// 处理日历格式转义
			if (rule.getType().equals("4")) {
				DBRule dbrule = query.getAndRemoveRule(rule.getCode());
				if (dbrule != null
						&& dbrule.getComparaSign().trim().equals(
								rule.getSign().trim())) {
					dbrule.setValue(TimeTool.getFormatTimeDate12(dbrule
							.getValue().replaceAll("-", "")
							+ "000000", rule.getTypepara()));
					query.addRule(dbrule);
				}
			}
			// 处理自定义格式
			if (rule.getSign().equals("SQL")) {
				DBRule dbrule = query.getAndRemoveRule(rule.getCode());
				if (dbrule != null) {
					query.addSqlRule(" and "
							+ rule.getSqlrule().replaceAll("_value_",
									dbrule.getValue()));
				}
			}
		}
	}

	/**
	 * 动态查询
	 * 
	 * @return
	 */
	public String report() {
		try {
			initQeuryPage();
			if (query == null) {
				query = new DataQuery();
			}
			query.setPagesize(entity.getReportmaxnum());
			query();
			// ------------------------开始报表
			inputStream = FarmReport.newInstance("queryReport.xls")
					.addParameter("name", entity.getName()).addParameter(
							"time",
							TimeTool.getFormatTimeDate12(TimeTool
									.getTimeDate14(), "yyyy-MM-dd HH:mm:ss"))
					.addParameter("username", getCurrentUser().getName())
					.addParameter("titles", titles).addParameter("datas",
							jsonResult.get("rows")).generate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return SUCCESS;
	}

	/**
	 * 构造查询页面
	 * 
	 * @return
	 */
	public String initQeuryPage() {
		try {
			entity = queryIMP.getQueryEntity(ids);
			rules = rulesIMP.getRulesByQueryId(ids);
			ruleTable = new ArrayList<List<Rules>>();
			titles = titleIMP.getTitlesByQueryId(ids);
			Collections.sort(titles, new Comparator<Title>() {
				@Override
				public int compare(Title o1, Title o2) {
					return o1.getSort() - o2.getSort();
				}
			});
			Collections.sort(rules, new Comparator<Rules>() {
				@Override
				public int compare(Rules o1, Rules o2) {
					return o1.getSort() - o2.getSort();
				}
			});
			// 构建入了table
			if (rules.size() > 0) {
				int rulesIndex = 0;
				int tdNum = 3;
				while (rulesIndex < rules.size()) {
					List<Rules> ruleTr = new ArrayList<Rules>();
					for (int i = 0; i < tdNum; i++) {
						if (rulesIndex < rules.size()) {
							ruleTr.add(rules.get(rulesIndex++).parseType());
						} else {
							ruleTr.add(new Rules());
						}
					}
					ruleTable.add(ruleTr);
				}
			}
			pageset = new PageSet(PageType.UPDATE, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.UPDATE,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	public String editSubmit() {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = queryIMP.editQueryEntity(entity, getCurrentUser());
			pageset = new PageSet(PageType.UPDATE, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.UPDATE,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	public String addSubmit() {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = queryIMP.insertQueryEntity(entity, getCurrentUser());
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.ADD,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	public String delSubmit() {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			for (String id : parseIds(ids)) {
				queryIMP.deleteQueryEntity(id, getCurrentUser());
			}
			pageset = new PageSet(PageType.ADD, CommitType.TRUE);
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.DEL,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	/**
	 * 跳转
	 * 
	 * @return
	 */
	public String forSend() {
		// TODO 自动生成代码,修改后请去除本注释
		return SUCCESS;
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 * 
	 * @return
	 */
	public String view() {
		try {
			if (type == null) {
				type = new Formcategory();
			}
			switch (pageset.getPageType()) {
			case (1): {// 新增
				break;
			}
			case (0): {// 展示
				entity = queryIMP.getQueryEntity(ids);
				type.setId(entity.getTypeid());
				break;
			}
			case (2): {// 修改
				entity = queryIMP.getQueryEntity(ids);
				type.setId(entity.getTypeid());
				break;
			}
			default:
				break;
			}
			if (type != null && type.getId() != null) {
				type = formcategoryIMP.getFormcategoryEntity(type.getId());
			}
		} catch (Exception e) {
			pageset = PageSet.initPageSet(pageset, PageType.OTHER,
					CommitType.FALSE, e);
		}
		return SUCCESS;
	}

	private final static QueryServiceInter queryIMP = (QueryServiceInter) BeanFactory
			.getBean("farm_forms_query_ProxyId");
	private final static FormcategoryServiceInter formcategoryIMP = (FormcategoryServiceInter) BeanFactory
			.getBean("farm_forms_Formcategory_ProxyId");
	private final static RulesServiceInter rulesIMP = (RulesServiceInter) BeanFactory
			.getBean("farm_forms_rules_ProxyId");
	private final static TitleServiceInter titleIMP = (TitleServiceInter) BeanFactory
			.getBean("farm_forms_title_ProxyId");

	// ----------------------------------------------------------------------------------
	public DataQuery getQuery() {
		return query;
	}

	public void setQuery(DataQuery query) {
		this.query = query;
	}

	public Query getEntity() {
		return entity;
	}

	public void setEntity(Query entity) {
		this.entity = entity;
	}

	public PageSet getPageset() {
		return pageset;
	}

	public void setPageset(PageSet pageset) {
		this.pageset = pageset;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public Map<String, Object> getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(Map<String, Object> jsonResult) {
		this.jsonResult = jsonResult;
	}

	public Formcategory getType() {
		return type;
	}

	public void setType(Formcategory type) {
		this.type = type;
	}

	public List<Rules> getRules() {
		return rules;
	}

	public void setRules(List<Rules> rules) {
		this.rules = rules;
	}

	public List<Title> getTitles() {
		return titles;
	}

	public void setTitles(List<Title> titles) {
		this.titles = titles;
	}

	public List<List<Rules>> getRuleTable() {
		return ruleTable;
	}

	public void setRuleTable(List<List<Rules>> ruleTable) {
		this.ruleTable = ruleTable;
	}

	public Map<String, List<Entry<String, String>>> getEnums() {
		return enums;
	}

	public void setEnums(Map<String, List<Entry<String, String>>> enums) {
		this.enums = enums;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	private static final Logger log = Logger.getLogger(QueryAction.class);
	private static final long serialVersionUID = 1L;
}
